<?php
class ObjectsController extends Zend_Controller_Action
{
	private $_acl;
	private $_user_info;
	private $_form;
	
    public function init()
    {
    	if(!Zend_Auth::getInstance()->hasIdentity()) $this->_redirect('index/login');
    	
    	$this->_user_info = Zend_Auth::getInstance()->getStorage()->read();
        $this->_acl = new Zwei_Admin_Acl($this->_user_info->user_name);
        
        
        $this->_helper->layout()->disableLayout();        
        $this->_form=new Zwei_Utils_Form();
        
       
        if(@$this->_form->format=='excel'){
 

			header('Content-type: application/vnd.ms-excel');
			header("Content-Disposition: attachment; filename={$this->_form->model}.xls");
			header("Pragma: no-cache");
			header("Expires: 0");
	
        }else{
	        $this->_helper->ContextSwitch
	        	->setAutoJsonSerialization(false)
	            ->addActionContext('index', 'json')
	            ->initContext();
        }        
    }
    
    /**
     * Retorna un json a partir de un objeto modelo, 
     * enviar nombre de clase modelo separada por "_" y sin sufijo "Model",
     * ej: enviar "model=solicitud_th" en lugar de "model=SolicitudThModel" 
     * @return json
     */

    public function indexAction()
    {
    	
    	/**
    	 * [TODO] Validar segun perfil de usuario autorizado a obtener estos datos
    	 * [TODO] En el caso de datos personales solo se debieran poder ver y editar los datos de UN reg. 
    	 */
    	
    	//enviar nombre de clase modelo separada por "_" y sin sufijo "Model",
    	//ej: enviar solicitud_th en lugar de SolicitudThModel"
    	$ClassModel=Zwei_Utils_String::toClassWord($this->_form->model)."Model";
    	
    	   	
    	
    	if(class_exists($ClassModel))
		{
	    	$model=new $ClassModel();
	    	//$model=new SolicitudThModel();
	        $this->view->collection = array();
	        
	        if(isset($this->_form->action))
	        {
	        	$data=array();
	        	$model->getAdapter()->getProfiler()->setEnabled(true);
	        	
		        if($this->_form->action=='add'){
		        	foreach ($this->_form->data as $i=>$v){
						$data[$i]=$v;
					}
					
					Zwei_Utils_Debug::write($model->getGeneratePass()."pfff");
					
					if($model->getGeneratePass()){
						$data["password"]=md5($data[$model->getGeneratePass()]);
					}
					
		        	$model->insert($data);
		        }elseif($this->_form->action=='delete'){
		        	if(!empty($this->_form->id)){
		        		$where=$model->getAdapter()->quoteInto("id = ?", $this->_form->id);
		        		$model->delete($where);	
		        	}
				}elseif($this->_form->action=='edit'){
					foreach ($this->_form->data as $i=>$v){
						$data[$i]=$v;
					}
					
			    	$where=$model->getAdapter()->quoteInto("id = ?", $this->_form->id);
		    		$model->update($data, $where);
				} 
				
				$query=$model->getAdapter()->getProfiler()->getLastQueryProfile()->getQuery();
				$query_params=print_r($model->getAdapter()->getProfiler()->getLastQueryProfile()->getQueryParams(),true);
				$model->getAdapter()->getProfiler()->setEnabled(false);
				
				// IMPORTANTE, LOG DE TRANSACCIONES: acá van query y usuario a un log de texto en caso de ser query INSERT, DELETE o UPDATE
				Zwei_Utils_Debug::write("[TRANSACTION:{$this->_form->action}]\nUser:{$this->_user_info->user_name}\nQuery:$query\nQuery Params:$query_params", false, "../log/transactions");
			}
			$select=$model->select();
			
			

	        if(!empty($this->_form->search)){

	        	if(!empty($this->_form->search_fields)){
	        		Zwei_Utils_Debug::write("search_fields:".$this->_form->search_fields);
	        		$search_fields=@explode(",",$this->_form->search_fields);
	        		if(!is_array($search_fields)) $search_fields=array($this->_form->search_fields);

	        		foreach ($search_fields as $s){
	        			//Zwei_Utils_Debug::write($s);
	        			if(!empty($s)){
	        				if(method_exists($model,"getName")){ $s=$model->getName().".".$s;} 
	        				
	        				if(preg_match("/^date_format,(.*)/", @$this->_form->search_format, $match))
	        				{
	        					//$mask=($match[1]) ? $match[1] : '%Y-%m-%d';//[FIXME] esto debiera ser parametrizable pero hay que solucionar el url_encode de "%" 
	        					$mask='%Y-%m-%d';
	        					if(@$this->_form->between=='1'){
	        						$search=explode(",",$this->_form->search);
	        						
	        						$select->where($model->getAdapter()->quoteInto("DATE_FORMAT($s,'$mask') >= ?", $search[0]));
	        						$select->where($model->getAdapter()->quoteInto("DATE_FORMAT($s,'$mask') <= ?", $search[1]));
	        					}else{
	        						$select->where($model->getAdapter()->quoteInto("DATE_FORMAT($s,'$mask') = ?", $this->_form->search));
	        					}		        					
	        				}else{
	        					$select->where($model->getAdapter()->quoteInto("$s LIKE ?", "%{$this->_form->search}%"));
	        				}	
	        			}	
	        		}
	        	}else{
					if(method_exists($model, 'getSearchFields')){
		        		$search_fields=$model->getSearchFields();
		        			
			        	foreach ($search_fields as $s){
	        				$select->orWhere($model->getAdapter()->quoteInto("$s LIKE ?", "%{$this->_form->search}%"));
		        		}	
		        	}
	        	}
	        	
	        }
	        
			if(isset($this->_form->id)){
				$my_id=(method_exists($model,"getPk")) ? $model->getPk() : "id"; 
				if(method_exists($model,"getName")) $my_id=$model->getName().".".$my_id; 
				$select->where($select->getAdapter()->quoteInto("$my_id = ?", $this->_form->id));
			}
	        
			Zwei_Utils_Debug::write($select->__toString());
        	$data=$model->fetchAll($select);		        	
	        
	        $i=0;

			if(@$this->_form->format=='excel'){
				$Table=new Zwei_Utils_Table();
				
				if(isset($this->_form->p)){
					$content=$Table->rowsetToHtml($data, $this->_form->p);
				}else{
					$content=$Table->rowsetToHtml($data);
				}	
				
			}else{
		        foreach ($data as $rowArray)
		        {
		        	$collection[$i]=array();
		            foreach ($rowArray as $column => $value)
		            {
		        		$collection[$i][$column] = utf8_encode(html_entity_decode($value));
		   			}
		   			$i++;
		        }
	  
		        //$str_collection=print_r($collection, true);
		        //Zwei_Utils_Debug::write($str_collection);
		        
		        if(method_exists($model,'getPrimary')){
		        	$id=$model->getPrimary();
					$content = new Zend_Dojo_Data($id[1], $collection);        	
		        }else{
		        	/*
		        	 * En caso de que no exista ninguna PK simple, inventamos un ID aca para que funcione el datastore
		        	 * (SOLO PARA LISTAR, NO USAR ESTA ID PARA EDITAR, MODIFICAR O ELIMINAR)
		        	 */
		        	if(!isset($collection[0]['id'])){
		        		for($j=0;$j<$i;$j++){
		        			$collection[$j]['id']=$j;
		        		}	
		        	}
		        	
		        	$content = new Zend_Dojo_Data('id', $collection);
		        }
				
				if(method_exists($model,'getLabel')){
					$content->setLabel($model->getLabel());
				}
			}	
			$this->view->content=$content;
				
		}
    }
}
